package cn.iocoder.yudao.module.system.util;

import cn.iocoder.yudao.module.system.controller.admin.auth.vo.AuthLoginRespVO;
import cn.iocoder.yudao.module.system.dal.dataobject.portal.PortalUserDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.enums.logger.LoginLogTypeEnum;
import cn.iocoder.yudao.module.system.service.auth.AdminAuthService;
import cn.iocoder.yudao.module.system.service.auth.PortalAuthService;
import cn.iocoder.yudao.module.system.service.portal.PortalUserService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jdk.nashorn.internal.ir.annotations.Reference;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Author: meiwanli
 * @Date: 2025-09-25 9:27
 */
@Slf4j
@Repository
public class HttpUtil {


    @Resource
    private PortalAuthService authService;

    @Resource
    private PortalUserService portalUserService;


    public AuthLoginRespVO sendPost(String tokenId, String cs) {
        String base64 = JiaMi.Base64(cs, tokenId);

        String result = "";
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        HttpPost httpPost = new HttpPost("http://192.168.0.12:8188/nvwa-certification/v1/ticket/verify");
        httpPost.setHeader("authorization-cer-ticket", base64);

        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("details", "true"));
        formparams.add(new BasicNameValuePair("ticketId", tokenId));
        formparams.add(new BasicNameValuePair("cs", cs));
        formparams.add(new BasicNameValuePair("appNo", "1012"));
        log.info("==============请求参数：" + formparams);
        UrlEncodedFormEntity uefEntity;


        CloseableHttpResponse response = null;
        try {
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(5000)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(5000)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(5000)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();

            // 将上面的配置信息 运用到这个Post请求里
            httpPost.setConfig(requestConfig);

            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httpPost.setEntity(uefEntity);
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            log.info("响应状态为：" + response.getStatusLine());

            if (entity != null) {
                result = EntityUtils.toString(entity);
                log.info("==============请求结果：" + result);

                // result转为json
                // 创建ObjectMapper实例
                ObjectMapper objectMapper = new ObjectMapper();
                // 解析JSON字符串为JsonNode
                JsonNode rootNode = objectMapper.readTree(result);
                if("true".equals(rootNode.get("success").asText())){
                    // 提取data中的字段
                    JsonNode dataNode = rootNode.get("data");
                    int validTime = dataNode.get("validTime").asInt();
                    JsonNode userNode = dataNode.get("user");
                    String username = userNode.get("name").asText();
                    PortalUserDO portalUser = portalUserService.getUserByUsername(username);
                    AuthLoginRespVO tokenAfterLoginSuccess = authService.createTokenAfterLoginSuccess(portalUser, username, LoginLogTypeEnum.LOGIN_SSO);
                    // 过期时间设置为当前时间+validTime，类型是LocalDateTime
                    tokenAfterLoginSuccess.setExpiresTime(LocalDateTime.now().plusSeconds(validTime));
                    return tokenAfterLoginSuccess;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

   void main(String[] args) {
        sendPost("c4c0295d0e7c499ebc36813637cfeb16", "NVWA");
    }
}
